/**
 * 作业答题
 */
var localStorageManagers = require("script/localStorageManagers.js");
//mui初始化
mui.init({
	swipeBack: false
});
FastClick.attach(document.body);
//plus初始化
mui.plusReady(function() {
	plusReady();
});
//plusReady
function plusReady() {
	//保存作业状态
	saveTaskStatus();
	//加载题目信息
	loadTimu();
	//切换题目
	mui('.top').on('tap', '.tihao1', clicktihao1); //已提交
	//左右滑动切换题目
	window.addEventListener("swipeleft", swipeLeft);
	window.addEventListener("swiperight", swipeRight);
	//提交作业
	mui('header').on('tap', '#tijiaotaskbtn', tijiaoTask);
	//保存作业
	mui('header').on('tap', '#savetaskbtn', saveTask);
	//编辑答案
	mui('.footbtndiv').on('tap', '.footbtnspan', footbtnspanEvent);
	//添加附件
	mui('.editdiv').on('tap','.addfilespan',addFile);
	//点击附件
	mui('.mui-content').on('tap','.f1',openFile);
	//编辑答案删除附件
	mui('#uploadfiles').on('tap','.delbtn',delUploadfile);
};
//加载题目
function loadTimu() {
	ajaxLoadtimu();
}
//ajax加载题目
function ajaxLoadtimu() {
	var self=plus.webview.currentWebview();
	var taskid = self.taskid;
	var taskname=self.taskname;
	if(taskname.length>15)taskname=taskname.substring(0,15)+'...';
	document.getElementById('fTaskid').value = taskid;
	document.getElementById('fTaskname').value=taskname;
	document.getElementById('tasknameh1').innerHTML=taskname;
	var userid = localStorageManagers.getUseridSession();
	var url = serverAjax + '/mobile/task/getTimusInfo.do';
	mui.ajax(url, {
		data: {
			taskid: taskid,
			userid: userid
		},
		type: 'post',
		dataType: 'json',
		timeout: 10000,
		success: function(data) {
			if (data == null || data.length == 0) return;
			buildTimuDivs(data);
		},
		error: function(e1, e2, e3) {
			ajaxErrorTip();
			console.log(e1);
		}
	});
}
//构建题目div
function buildTimuDivs(timus) {
	var timusEle = document.getElementById('elist1');

	for (var i = 0; i < timus.length; i++) {
		var timu = timus[i];
		//设置题号
		settihao(timu, i);
		//题目附件
		var filestr1 = '';
		for (var j = 0; j < timu.files.length; j++) {
			var path =  timu.files[j].path;
			var name=timu.files[j].name;
			name=viewFilename(name);
			filestr1 += '<span class="f1" path="' + path + '">' + name+ '</span>';
		}

		//题目
		var act = '';
		if (i == 0) act = 'act';
		var timustr = '<div class="task task1 ' + act + '" id="task1_' + timu.id + '">';
		timustr += '<div class="task-content">';
		timustr += '<div class="c1">' + timu.question + '</div>';
		timustr += '<div class="c2">';
		timustr += filestr1;
		timustr += '</div>';
		timustr += '</div>';
		timustr += '<div class="task-daan" id="task-daan_' + timu.id + '"></div>';
		timustr += '</div>';
		timusEle.innerHTML = timusEle.innerHTML + timustr;
		//题目答案
		setdaan(timu.daan);
	}
}
function viewFilename(name){
	if(name.length>6)name=name.substring(0,6)+'...';
	return name;
}
//设置题号
function settihao(timu, i) {
	var topEle = document.getElementById('top1');
	var tihaostr = '';
	var act = '';
	if (i == 0) {
		act = 'act';
		document.getElementById('fTihao').value = timu.id;
	}
	tihaostr = '<span class="tihao tihao1 ' + act + '" tihao="' + timu.id + '">' + (i + 1) + '</span>';
	topEle.innerHTML = topEle.innerHTML + tihaostr;
}
//设置答案
function setdaan(daan) {
	if (daan != undefined) {
		
		var filesstr = '';
		for (var j = 0; j < daan.files.length; j++) {
			var path =  daan.files[j].path;
			var name=daan.files[j].name;
			name=viewFilename(name);
			filesstr += '<span class="f1" path="' + path + '" name="'+daan.files[j].name+'" fileid="'+daan.files[j].id+'">' + name+ '</span>';
		}
		
		var daanEle = document.getElementById('task-daan_' + daan.extId);
		var daans = '<div class="t1">答案:</div>';
		daans += '<div class="t2" id="task-daan-content_' + daan.extId + '">' + daan.answer + '</div>';
		daans += '<div class="c2" id="task-daan-files_' + daan.extId + '">';
		daans += filesstr;
		daans += '</div>';
		daanEle.innerHTML = daans;
	}
}
//已提交的题目
function clicktihao1() {
	var type=document.getElementById('footbtnspan').getAttribute('type');
	if(type==2){
		mui.toast('当前题目正在编辑,不能切换题目');
		return;
	}
	//题号按钮颜色改变
	var tihaos = document.getElementsByClassName('tihao1');
	for (var i = 0; i < tihaos.length; i++) {
		tihaos[i].className = 'tihao tihao1';
	}
	this.className = 'tihao tihao1 act';
	//显示对应题目
	var tasks = document.getElementsByClassName('task1');
	for (var i = 0; i < tasks.length; i++) {
		tasks[i].className = 'task task1';
	}
	var tihao = this.getAttribute('tihao');
	var timuDiv = document.getElementById('task1_' + tihao);
	timuDiv.className = 'task task1 act';
	document.getElementById('fTihao').value = tihao;
};
//提交作业
function tijiaoTask() {
	var istijiao = confirm('您确定要像老师提交本次作业吗?');
	if (!istijiao) return;
		var taskid = document.getElementById('fTaskid').value;
		var userid = localStorageManagers.getUseridSession();
		var url = serverAjax + '/mobile/task/submitOrCancelTask.do';
		mui.ajax(url, {
			data: {
				userid: userid,
				taskid: taskid,
				type: 1
			},
			type: 'post',
			dataType: 'json',
			timeout: 10000,
			success: function(data) {
				if (data == null || data.length == 0) return;
				if (data == 1) {
					mui.toast('提交作业成功');
					var parentWebView = plus.webview.getWebviewById("selfcenter/task/taskindex");
	                parentWebView.evalJS("loadTask()");
					mui.back();
					//this.src = '../../images/task_3.png';
					//this.className = 'canceltask';
				} else if (data == 0) {
					mui.toast('还未开始做作业');
				}
			},
			error: function(e1, e2, e3) {
				ajaxErrorTip();
				console.log(e1);
			}
		});
};
//保存作业
function saveTask() {
	mui.toast('已保存');
}
//编辑答案
function footbtnspanEvent() {
	var type = this.getAttribute("type");
	if (type == 1)
		editDaan(this);
	if (type == 2)
		editDaanFinish(this);

};
//点击编辑答案
function editDaan(ts) {
	ts.innerHTML = '完成';
	document.getElementById('daancontent').value = '';
	document.getElementById('uploadfiles').innerHTML='';
	ts.setAttribute("type", "2");
	document.getElementById('editdiv').style.display = 'block';
	var tihao = document.getElementById('fTihao').value;
	toggleDaandisplay(tihao, 'none');
	//设置答案编辑框
	var extId = document.getElementById('fTihao').value;
	var daanContentEle = document.getElementById('task-daan-content_' + extId);
	if (daanContentEle != null && daanContentEle != undefined) document.getElementById('daancontent').value = daanContentEle.innerText;
	
	//设置附件
	var daanFilesEle = document.getElementById('task-daan-files_' + extId);
	var f1s=daanFilesEle.getElementsByClassName('f1');
	//var pathstr=daanFilesEle.getAttribute('paths');//答案附件路径
	//var namestr=daanFilesEle.getAttribute('names');//答案附件名称
	//var paths=pathstr.split('|');
	//var names=namestr.split('|');
	for(var i=0;i<f1s.length;i++){
		var path=f1s[i].getAttribute('path');
		var name=f1s[i].getAttribute('name');
		var fileid=f1s[i].getAttribute('fileid');
		if(path=='')continue;
		var nameview=name;
		nameview=viewFilename(nameview);
		var filestr='<span class="f1 uploadpath" path="'+path+'" name="'+name+'" fileid="'+fileid+'">'+nameview+'<span class="delbtn">删除</span></span>';
		document.getElementById('uploadfiles').innerHTML=document.getElementById('uploadfiles').innerHTML+filestr;
	}
	
};
//编辑完成
function editDaanFinish(ts) {
	ts.innerHTML = '编辑答案';
	ts.setAttribute("type", "1");
	document.getElementById('editdiv').style.display = 'none';
	var tihao = document.getElementById('fTihao').value;
	toggleDaandisplay(tihao, 'block');
	//设置编辑后答案
	var daancontent = document.getElementById('daancontent').value;
	var extId = document.getElementById('fTihao').value;
	var taskid = document.getElementById('fTaskid').value;
	var userid = localStorageManagers.getUseridSession();
	//files
	var files=new Array();
	var eles=document.getElementsByClassName('uploadpath');
	for(var i=0;i<eles.length;i++){
		var path=eles[i].getAttribute('path');
		var name=eles[i].getAttribute('name');
		var fileid=eles[i].getAttribute('fileid');
		var data={
				"path":path,
				"name":name,
				"id":fileid
		};
		files.push(data);
	}
	
	//if(paths.length>0)paths=paths.substring(0,paths.length-1);
	var daan1 = {
		answer: daancontent,
		extId: extId,
		files: files,
		taskid: taskid,
		userid: userid
	}
	var filestr=JSON.stringify(files);
	var daan2 = {
		answer: daancontent,
		extId: extId,
		files: filestr,
		taskid: taskid,
		userid: userid
	}
	setdaan(daan1);
	//保存答案
	saveDaan(daan2);
}
//保存答案
function saveDaan(daan) {
	var delfiles='';
	if(delFiles!=null&&delFiles.length>0)delfiles=delFiles.join(',');
	var url = serverAjax + '/mobile/task/saveStudentWork.do?delfiles='+delfiles;
	mui.ajax(url, {
		data: daan,
		type: 'post',
		dataType: 'json',
		timeout: 10000,
		success: function(data) {delFiles=new Array();},
		error: function(e1, e2, e3) {
			ajaxErrorTip();
			console.log(e1);
			delFiles=new Array();
		}
	});
}
//设置答案隐藏
function toggleDaandisplay(tihao, distype) {
	document.getElementById('task-daan_' + tihao).style.display = distype;
}
//保存作业状态
function saveTaskStatus() {
	var taskid = plus.webview.currentWebview().taskid;
	var userid = localStorageManagers.getUseridSession();
	var url = serverAjax + '/mobile/task/saveWorkStatus.do';
	mui.ajax(url, {
		data: {
			taskid: taskid,
			userid: userid
		},
		type: 'post',
		dataType: 'json',
		timeout: 10000,
		success: function(data) {

		},
		error: function(e1, e2, e3) {
			ajaxErrorTip();
			console.log(e1);
		}
	});
};
//添加附件
function addFile(){
	plus.gallery.pick(function(path) {
						if (0 != path.indexOf("file://")) {
							path = "file://" + path;
						}
							addFile2(path);
					}, function(e) {}, {
						filter: "image"
					});
};
//添加附件
function addFile2(path){
			//创建上传任务
			var w=plus.nativeUI.showWaiting();
			var uploadImgeUrl = serverAjax+"/mobile/task/uploadFile.do";
			//uploadImgeUrl = _serverURL + uploadImgeUrl;
			var task = plus.uploader.createUpload(uploadImgeUrl,{method:'POST', blocksize:0,retry:2,timeout:100},function(t, status){
				var uploadjson = JSON.parse(t.responseText);
				w.close();
				if(status==200){
					//plus.nativeUI.toast('上传成功');
					var name=uploadjson.touxiang;
					name=viewFilename(name);
					var filestr='<span class="f1 uploadpath" path="'+uploadjson.ResPath+'" name="'+uploadjson.touxiang+'" fileid="0">'+name+'<span class="delbtn">删除</span></span>';
					document.getElementById('uploadfiles').innerHTML=document.getElementById('uploadfiles').innerHTML+filestr;
				}else{
					plus.nativeUI.toast(obj.message);
				}
			});
			//设置上传文件
			var index=path.lastIndexOf('/');
			var name=path.substring(index+1);
			task.addFile(path, {
						key: "touxiang"
					});
			//开始上传
			task.start();
}
//查看附件
function openFile(){

	var path=this.getAttribute('path');
	path=fileServerAjax+path;
	plus.runtime.openURL(path, {}, function ( e ) {
			                  plus.nativeUI.alert( "无法打开'"+suffix+"'格式的文件,请安装相关应用." );
		             } );
};
//删除附件
var delFiles=new Array();
function delUploadfile(e){
	e.stopPropagation();
	var fileid=this.parentNode.getAttribute('fileid');
	if(fileid>0)delFiles.push(fileid);
	this.parentNode.parentNode.removeChild(this.parentNode);
}

//左滑切换题目
function swipeLeft(){
	if(document.getElementById('editdiv').style.display == 'block'){
		mui.toast('请先答完当前题目再切换');
		return;
	}
	var tihaos = document.getElementsByClassName('tihao1');
	var nextTihao=null;
	for (var i = 0; i < tihaos.length-1; i++) {
		if(tihaos[i].className.indexOf('act')!=-1)
		nextTihao=tihaos[i+1];
		tihaos[i].className = 'tihao tihao1';
	}
	if(nextTihao!=null){
	   nextTihao.className = 'tihao tihao1 act';
	   //显示对应题目
	var exams = document.getElementsByClassName('task1');
	for (var i = 0; i < exams.length; i++) {
		exams[i].className = 'task task1';
	}
	var tihao = nextTihao.getAttribute('tihao');
	var timuDiv = document.getElementById('task1_' + tihao);
	timuDiv.className = 'task task1 act';
	document.getElementById('fTihao').value=tihao;
	}
};
//右滑切换题目
function swipeRight(){
	if(document.getElementById('editdiv').style.display == 'block'){
		mui.toast('请先答完当前题目再切换');
		return;
	}
	var tihaos = document.getElementsByClassName('tihao1');
	var nextTihao=null;
	for (var i = 1; i < tihaos.length; i++) {
		if(tihaos[i].className.indexOf('act')!=-1)
		nextTihao=tihaos[i-1];
		tihaos[i].className = 'tihao tihao1';
	}
	if(nextTihao!=null){
	    nextTihao.className = 'tihao tihao1 act';
	    //显示对应题目
	var exams = document.getElementsByClassName('task1');
	for (var i = 0; i < exams.length; i++) {
		exams[i].className = 'task task1';
	}
	var tihao = nextTihao.getAttribute('tihao');
	var timuDiv = document.getElementById('task1_' + tihao);
	timuDiv.className = 'task task1 act';
	document.getElementById('fTihao').value=tihao;
	}
};